package paper.web.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import keter.exception.KeterValidationException;

import org.apache.commons.codec.binary.Base64;
import org.springframework.web.multipart.MultipartFile;

import paper.util.ConfigConstant;

public class WebUtil {
	
	/**
	 * <p>Method ：makeDownload
	 * <p>Description : 文件下载通用方法
	 * @param request
	 * @param response
	 * @param localFileUri    本地文件地址
	 * @param fileName       (返回给浏览器的)文件名称
	 * @throws UnsupportedEncodingException
	 * @throws FileNotFoundException
	 * @throws IOException 
	 * @author  gulixing@msn.com
	 * @version 1.0.0
	 */
	public static void makeDownload(HttpServletRequest request, HttpServletResponse response,String localFileUri,String fileName)
			throws UnsupportedEncodingException, FileNotFoundException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		long fileLength = new File(localFileUri).length();
		String contentType = "application/octet-stream";  
		response.setContentType(contentType);
		response.setHeader("Content-disposition", "attachment; filename="+ processFileName(request,fileName));
		response.setHeader("Content-Length", String.valueOf(fileLength));
		bis = new BufferedInputStream(new FileInputStream(localFileUri));
		bos = new BufferedOutputStream(response.getOutputStream());
		byte[] buff = new byte[2048];
		int bytesRead;
		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
			bos.write(buff, 0, bytesRead);
		}
		bis.close();
		bos.close();
	}
	
	/**
	 * <p>Method ：processFileName
	 * <p>Description : 识别浏览器类型，避免文件名中文乱码问题
	 * @param request
	 * @param fileName
	 * @return
	 * @throws UnsupportedEncodingException 
	 * @author  gulixing@msn.com
	 * @version 1.0.0
	 */
	private static String processFileName(HttpServletRequest request,String fileName) throws UnsupportedEncodingException{
		String agent = (String)request.getHeader("USER-AGENT");    
		String enableFileName=fileName;
		if(agent != null && agent.indexOf("MSIE") == -1) {// FF      
		    enableFileName = "=?UTF-8?B?" + (new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?=";    
		} else { // IE      
		    enableFileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");    
		} 
		return enableFileName;
	}
	

	/**
	 * <p>Method ：validateUploadFile
	 * <p>Description : 功能描述
	 * @param file
	 * @param ext    扩展名
	 * @param size   文件大小
	 * @param model
	 * @return 
	 * @author  gulixing@msn.com
	 * @version 1.0.0
	 * @throws KeterValidationException 
	 */
	public static void validateUploadFile(MultipartFile file,String extAllow,Long size) throws KeterValidationException{
		String fileName = file.getOriginalFilename();
		String ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
        if(!extAllow.contains(ext)){
        	throw new KeterValidationException("非法的文件格式:["+ext+"]！");
        }
        if (file.getSize() > size) {
        	throw new KeterValidationException("文件大小不能超过"+ConfigConstant.getFileMaxSizeText(size)+"！");
        }
	}
	
	
//	/**
//	 * <p>Method ：translateStatus
//	 * <p>Description : 将status进行转码处理
//	 * @param r 
//	 * @author  gulixing@msn.com
//	 * @version 1.0.0
//	 */
//	public static void translateStatus(CodeListService service,BasePaper bp){
//		Map<String, String>map = service.findByCodeKind("AUDIT-STATUS");
//		bp.setStatus(map.get(bp.getStatus()));
//	}
}
